
<template>
  <span class="fileViewer" @click="viewFile">
    <slot />
    <el-dialog
      class="fileViewerDialog"
      :visible="fileViewDialogVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      width="90vw"
      :before-close="handleClose">
      <iframe ref="iframe" v-loading="loading" :src="src" style="" class="iframe" element-loading-text="页面正在拼命加载中" @load="onLoad" />
    </el-dialog>
  </span>
</template>
<script>
import { getViewUrl } from './util.js'
export default {
  name: 'FileViewer',
  props: {
    type: {
      type: Number,
      required: false,
      default: 127
    },
    url: {
      type: String,
      required: false,
      default: ''
    },
    title: {
      type: String,
      required: false,
      default: '默认'
    },
    // 打开模式，默认对话框 dialog：对话框 page：页面
    mode: {
      type: String,
      required: false,
      default: 'dialog'
    }

  },
  data() {
    return {
      fileType: 127,
      fileViewDialogVisible: false,
      loading: true,
      src: null
    }
  },
  watch: {
    type: function(val) {
      if (val) {
        this.fileType = val
      }
    }
  },
  created() {
    if (this.type) {
      this.fileType = this.type
    }
  },
  mounted() {
    window.addEventListener('message', (e) => {
      if (e.data.closeIframe) {
        this.fileViewDialogVisible = false
      }
    })
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    onLoad() {
      this.loading = false
    },
    viewFile() {
      if (this.fileType < 0) {
        this.$emit('click')
        return
      }
      var url = this.$router.resolve({ path: getViewUrl(this.url, this.fileType, 'view', this.title) }).href
      if (this.mode === 'page') {
        window.open(url)
      } else {
        this.fileViewDialogVisible = true
        this.src = url + '?mode=dialog'
      }
    }
  }
}
</script>
<style lang="scss">
.fileViewer{
  display: flex;
  flex-direction: row;
  cursor: pointer;
  align-items: center;
}
.fileViewerDialog{
  margin: 0 auto !important;
  overflow: hidden;
  .el-dialog{
    margin-top: 5vh !important;
  }
  .el-dialog__body {
    height: calc(90vh);
    z-index: 100000;
    padding: 0;
    overflow: hidden;
  }
  .el-dialog__header{
    display: none;
  }
  .iframe{
    width:100%;
    height:100%;
    border:none;
    .footer{
        display: none;
    }
  }
}
</style>
